<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工号" prop="empNo">
        <el-input
          v-model="queryParams.empNo"
          placeholder="请输入工号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="empName">
        <el-input
          v-model="queryParams.empName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职位" prop="posName">
        <el-input
          v-model="queryParams.posName"
          placeholder="请输入职位名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工号" align="center" prop="empNo" />
      <el-table-column label="姓名" align="center" prop="empName" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="职位名称" align="center" prop="posName" />
      <el-table-column label="职级" align="center" prop="levelId">
        <template v-slot="scope">
          <span>C{{ scope.row.levelId ? scope.row.levelId.toString().padStart(2, '0') : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入职日期" align="center" prop="entryDate" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.entryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total>0"
      :total="total"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="getList"
      @size-change="handleSizeChange">
    </el-pagination>

    <!-- 添加或修改员工对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="employeeRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工号" prop="empNo">
              <el-input v-model="form.empNo" placeholder="请输入工号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="empName">
              <el-input v-model="form.empName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="18" :max="65" placeholder="请输入年龄" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker
                v-model="form.entryDate"
                type="date"
                placeholder="选择入职日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试用期时长" prop="probationDays">
              <el-input-number v-model="form.probationDays" :min="0" placeholder="试用期天数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="转正日期" prop="regDate">
              <el-date-picker
                v-model="form.regDate"
                type="date"
                placeholder="选择转正日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择合同类型">
                <el-option label="正式合同" value="正式合同" />
                <el-option label="实习合同" value="实习合同" />
                <el-option label="临时合同" value="临时合同" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同期限" prop="contractYears">
              <el-input-number v-model="form.contractYears" :min="0" :precision="1" placeholder="合同期限(年)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同到期日期" prop="contractEndDate">
              <el-date-picker
                v-model="form.contractEndDate"
                type="date"
                placeholder="选择合同到期日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作年限" prop="workYears">
              <el-input-number v-model="form.workYears" :min="0" :precision="1" placeholder="工作年限" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="base城市" prop="baseCity">
              <el-input v-model="form.baseCity" placeholder="请输入base城市" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="直属领导" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入直属领导" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位名称" prop="posName">
              <el-input v-model="form.posName" placeholder="请输入职位名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="职级" prop="levelId">
              <el-select v-model="form.levelId" placeholder="请选择职级" style="width: 100%">
                <el-option
                  v-for="level in jobLevelList"
                  :key="level.levelId"
                  :label="level.levelName"
                  :value="level.levelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee } from "@/api/employee/employee";
import { parseTime } from "@/utils/index";

export default {
  name: "Employee",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工表格数据
      employeeList: [],
      // 职级列表
      jobLevelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        empNo: null,
        empName: null,
        posName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        empNo: [
          { required: true, message: "工号不能为空", trigger: "blur" }
        ],
        empName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "身份证号格式不正确", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" },
          { type: 'number', min: 18, max: 65, message: "年龄必须在18-65之间", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
        ],
        entryDate: [
          { required: true, message: "入职日期不能为空", trigger: "change" }
        ],
        levelId: [
          { required: true, message: "职级不能为空", trigger: "change" }
        ]
      }
    };
  },
  async created() {
    console.log('员工管理页面初始化开始')
    
    // 确保用户信息已加载
    if (!this.$store.getters.name) {
      await this.$store.dispatch('user/getInfo')
    }
    
    console.log('当前用户信息:', {
      name: this.$store.getters.name,
      roles: this.$store.getters.roles,
      role: this.$store.getters.role
    })
    
    // 先加载职级列表
    this.getJobLevelList()
    
    // 尝试从API获取数据，如果失败则使用模拟数据
    this.getList()
    
    console.log('员工管理页面初始化完成')
  },
  methods: {
    /** 检查管理员权限 */
    checkAdminPermission() {
      const roles = this.$store.getters.roles
      const role = this.$store.getters.role
      console.log('当前用户角色信息:', { roles, role })
      return roles && roles.includes('admin')
    },
    /** 查询员工列表 */
    getList() {
      this.loading = true
      
      listEmployee(this.queryParams).then(response => {
        console.log('员工列表响应:', response)
        
        if (response && response.code === 200) {
          // 根据后端接口，可能返回的是 List<Employee> 或者分页结构
          if (Array.isArray(response.data)) {
            // 直接是数组
            this.employeeList = response.data || []
            this.total = response.data ? response.data.length : 0
            console.log('使用API数组格式，数据长度:', this.employeeList.length)
          } else if (response.data && response.data.rows) {
            // 分页结构
            this.employeeList = response.data.rows || []
            this.total = response.data.total || 0
            console.log('使用API分页格式，数据长度:', this.employeeList.length)
          } else if (response.data && Array.isArray(response.data)) {
            // 另一种可能的数组格式
            this.employeeList = response.data || []
            this.total = response.data ? response.data.length : 0
            console.log('使用API直接数组格式，数据长度:', this.employeeList.length)
          }
          console.log('API数据加载成功:', this.employeeList)
        } else {
          console.log('API返回错误，使用模拟数据')
          this.getMockData()
        }
        this.loading = false
      }).catch(error => {
        console.error('API调用失败，使用模拟数据:', error)
        this.getMockData()
        this.loading = false
      })
    },
    /** 获取模拟数据 */
    getMockData() {
      this.employeeList = [
        {
          empId: 1,
          empNo: 'E001',
          empName: '张三',
          gender: '男',
          age: 25,
          phone: '13800138001',
          posName: '软件工程师',
          levelId: 1,
          entryDate: '2024-01-15'
        },
        {
          empId: 2,
          empNo: 'E002',
          empName: '李四',
          gender: '女',
          age: 28,
          phone: '13800138002',
          posName: '产品经理',
          levelId: 2,
          entryDate: '2024-02-01'
        },
        {
          empId: 3,
          empNo: 'E003',
          empName: '王五',
          gender: '男',
          age: 30,
          phone: '13800138003',
          posName: '项目经理',
          levelId: 3,
          entryDate: '2023-12-01'
        },
        {
          empId: 4,
          empNo: 'E004',
          empName: '赵六',
          gender: '女',
          age: 26,
          phone: '13800138004',
          posName: 'UI设计师',
          levelId: 2,
          entryDate: '2024-03-01'
        },
        {
          empId: 5,
          empNo: 'E005',
          empName: '钱七',
          gender: '男',
          age: 32,
          phone: '13800138005',
          posName: '技术总监',
          levelId: 5,
          entryDate: '2023-06-01'
        }
      ]
      this.total = this.employeeList.length
      console.log('使用模拟数据，共', this.employeeList.length, '条记录')
    },
    /** 查询职级列表 */
    getJobLevelList() {
      // 直接使用写死的职级数据 C01-C30
      this.jobLevelList = []
      for (let i = 1; i <= 30; i++) {
        this.jobLevelList.push({
          levelId: i,
          levelName: `C${i.toString().padStart(2, '0')}`
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        empId: null,
        empNo: null,
        empName: null,
        idCard: null,
        gender: null,
        age: null,
        entryDate: null,
        probationDays: null,
        regDate: null,
        contractType: null,
        contractYears: null,
        contractEndDate: null,
        workYears: null,
        phone: null,
        baseCity: null,
        leader: null,
        posName: null,
        levelId: null
      };
      this.resetForm("employeeRef");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryRef')
      this.handleQuery()
    },
    /** 分页大小改变 */
    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.empId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加员工'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const empId = row.empId || this.ids
      getEmployee(empId).then(response => {
        if (response.code === 200) {
          this.form = response.data
          this.open = true
          this.title = '修改员工'
        } else {
          this.$message.error(response.message || '获取员工详情失败')
        }
      }).catch(error => {
        console.error('获取员工详情失败:', error)
        this.$message.error('获取员工详情失败')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['employeeRef'].validate(valid => {
        if (valid) {
          if (this.form.empId != null) {
            updateEmployee(this.form).then(response => {
              if (response.code === 200) {
                this.$message.success('修改成功')
                this.open = false
                this.getList()
              } else {
                this.$message.error(response.message || '修改失败')
              }
            }).catch(error => {
              console.error('修改员工失败:', error)
              this.$message.error('修改失败')
            })
          } else {
            addEmployee(this.form).then(response => {
              if (response.code === 200) {
                this.$message.success('新增成功')
                this.open = false
                this.getList()
              } else {
                this.$message.error(response.message || '新增失败')
              }
            }).catch(error => {
              console.error('新增员工失败:', error)
              this.$message.error('新增失败')
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const empId = row.empId || this.ids[0]
      this.$confirm('是否确认删除该员工？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delEmployee(empId).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        }).catch(error => {
          console.error('删除员工失败:', error)
          this.$message.error('删除失败')
        })
      }).catch(() => {
        // 用户取消删除
      })
    }
  }
}
</script>